import React, { useState, useEffect, useRef } from 'react';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import { TjFilter, TjHeader } from '@/tjComponents';
import { Select } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { useForm } from 'antd/es/form/Form';
import SdConfig from './components/SdConfig';
import MxConfig from './components/MxConfig';
import XjConfig from './components/XjConfig';
import SxConfig from './components/SxConfig';
import NxConfig from './components/NxConfig';
import { mxFilter, sdFilter, sxFilter, xjFilter, nxFilter } from './helper';
import type { ProvinceType } from '@/hooks/useRequestPowerAfterInit';
import type { ITjFormItemProps } from '@/tjComponents/TjForm/TjFormItem';
import './index.less';
import { connect } from 'umi';
import TRDefault from '@/tool/components/TRTheme/TRDefault';

// 只针对设置默认时间
const defaultFilterValues = {
  sxValues1: {
    year: moment(),
  },
  sxValues2: {
    year: [moment(), moment()],
  },
  nxValues: {
    year: moment(),
  },
  xjValues: {
    year: moment(),
  },
  sdValues: {
    year: [moment(), moment()],
  },
  mxValues: {
    year: [moment(), moment()],
  },
};

const StationTradeParamConfig: React.FC<IStationTradeParamConfigProps> = (props) => {
  const [form] = useForm();
  const [filterItem, setFilterItem] = useState<ITjFormItemProps[]>([]);
  const [filterValues, setFilterValues] = useState<any>({});
  const [currentProvinceInfo, setCurrentProvinceInfo] = useState<any>();
  const { initLoading, province, errorMsg, treeData } = useRequestPowerAfterInit(
    '/power/dataPower/common/StationTradeParamConfig/t_station',
    (parmas) => {
      setCurrentProvinceInfo(parmas);
      setCurrentProvinceId(parmas.value);
    },
    {
      convertResult: '2',
      matchFirst: 0,
    },
  );
  const [sxTabActiveKey, setSxTabActiveKey] = useState<string>('1');
  const [currentProvinceId, setCurrentProvinceId] = useState<string>();
  const [loading, setLoading] = useState<boolean>(false);
  const isFirst = useRef<boolean>(true);

  const buildFilterItem = (marketId: string) => {
    let arr: ITjFormItemProps[] = [];
    form.resetFields();
    const values = setDefaultFilterValue(marketId);
    if (marketId === 'PHBSX') {
      arr = sxFilter(sxTabActiveKey, treeData, currentProvinceInfo.value);
    }
    if (marketId === 'PXBNX') {
      arr = nxFilter;
    }
    if (marketId === 'PXBXJ') {
      arr = xjFilter;
    }
    if (marketId === 'PXBMX') {
      arr = mxFilter(treeData, currentProvinceInfo.value);
    }
    if (marketId === 'PHBSD') {
      arr = sdFilter(treeData, currentProvinceInfo.value);
    }

    setFilterItem(arr);
    const newValues = {
      marketId: currentProvinceInfo.value,
      ...values,
    };
    form.setFieldsValue(newValues);

    if (isFirst.current || marketId === 'PHBSX') {
      onSearch(newValues);
      isFirst.current = false;
    }
  };

  const changeProvince = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      setCurrentProvinceInfo(item);
    }
  };

  const onSearch = (values: any) => {
    setCurrentProvinceId(values.marketId);
    setFilterValues(values);
  };

  const onReset = () => {
    const values: any = form.getFieldsValue();
    const marketId = _.get(values, 'marketId', undefined);
    if (marketId) {
      const data = setDefaultFilterValue(marketId);
      form.setFieldsValue(data);
      setFilterValues(data);
    }
  };

  const setDefaultFilterValue = (marketId: string) => {
    let data: any = {};
    if (marketId === 'PHBSX') {
      if (sxTabActiveKey === '1') {
        data = defaultFilterValues.sxValues1;
      }
      if (sxTabActiveKey === '2') {
        data = defaultFilterValues.sxValues2;
        data.stationIdList = currentProvinceInfo.stations.map((v: any) => v.stationId);
      }
    }
    if (marketId === 'PXBNX') {
      data = defaultFilterValues.nxValues;
    }
    if (marketId === 'PXBXJ') {
      data = defaultFilterValues.xjValues;
    }
    if (marketId === 'PXBMX') {
      data = defaultFilterValues.mxValues;
      data.stationIdList = currentProvinceInfo.stations.map((v: any) => v.stationId);
    }
    if (marketId === 'PHBSD') {
      data = defaultFilterValues.sdValues;
      data.stationIdList = currentProvinceInfo.stations.map((v: any) => v.stationId);
    }
    return data;
  };

  useEffect(() => {
    if (currentProvinceInfo) {
      buildFilterItem(currentProvinceInfo.value);
    }
  }, [currentProvinceInfo, sxTabActiveKey]);

  return (
    <div className="station-trade-param-config">
      <TjHeader
        left={
          <TjFilter
            form={form}
            items={[
              {
                name: 'marketId',
                rules: [{ required: true, message: '请选择交易中心' }],
                render: (
                  <Select
                    options={province}
                    style={{ width: 180 }}
                    loading={initLoading}
                    onChange={changeProvince}
                  />
                ),
              },
              ...filterItem,
            ]}
            onSearch={onSearch}
            onReset={onReset}
            loading={loading || initLoading}
          />
        }
      />

      {currentProvinceId === 'PHBSX' && (
        <SxConfig
          defaultActiveKey={sxTabActiveKey}
          onTabChange={(key) => setSxTabActiveKey(key)}
          filterValues={filterValues}
          marketId={currentProvinceInfo.value}
          marketName={currentProvinceInfo.label}
          currentProvinceInfo={currentProvinceInfo}
          menuCode={props.menuCode}
          treeData={treeData}
          strategyType="basic_strategy"
          changeGlobalLoading={(status) => setLoading(status)}
        />
      )}

      {currentProvinceId === 'PXBNX' && (
        <NxConfig
          filterValues={filterValues}
          marketId={currentProvinceInfo.value}
          marketName={currentProvinceInfo.label}
          changeGlobalLoading={(status) => setLoading(status)}
        />
      )}

      {currentProvinceId === 'PXBXJ' && (
        <XjConfig
          filterValues={filterValues}
          marketId={currentProvinceInfo.value}
          marketName={currentProvinceInfo.label}
          changeGlobalLoading={(status) => setLoading(status)}
        />
      )}

      {currentProvinceId === 'PHBSD' && (
        <SdConfig
          filterValues={filterValues}
          marketId={currentProvinceInfo.value}
          marketName={currentProvinceInfo.label}
          menuCode={props.menuCode}
          strategyType="basic_strategy"
          treeData={treeData}
          currentProvinceInfo={currentProvinceInfo}
          changeGlobalLoading={(status) => setLoading(status)}
        />
      )}

      {currentProvinceId === 'PXBMX' && (
        <MxConfig
          filterValues={filterValues}
          marketId={currentProvinceInfo.value}
          marketName={currentProvinceInfo.label}
          menuCode={props.menuCode}
          strategyType="common_strategy"
          treeData={treeData}
          currentProvinceInfo={currentProvinceInfo}
          changeGlobalLoading={(status) => setLoading(status)}
        />
      )}

      {currentProvinceId &&
        !['PHBSX', 'PXBXJ', 'PXBNX', 'PHBSD', 'PXBMX'].includes(currentProvinceId) && (
          <TRDefault type="empty" />
        )}
    </div>
  );
};

interface IStationTradeParamConfigProps {
  menuCode: string;
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
}))(StationTradeParamConfig);
